<template>
    <div class="common questionAdd">
        <innerCommon 
            :location="location"
        >
            <template slot="left">
                <span>题目列表</span>
                <a-button-group style="margin-left:10px;">
                    <a-button @click="allSelect()"><a-checkbox :checked="allChecked">全选</a-checkbox></a-button>
                    <a-button icon='arrows-alt' @click="showAllAnswer">{{showBtnText}}</a-button>
                    <a-button icon='delete' @click="deleteLot">删除</a-button>
                </a-button-group>
                <a-select allowClear style="margin-left:10px;width: 120px" placeholder="全部题型" @change="selectKind">
                    <a-select-option v-for="item in questionTypeList" :key="item.types" :value="item.types">{{item.value}}</a-select-option>
                </a-select>
            </template>
            <div slot="right">
                <a-popover placement="bottom">
                    <template slot="content">
                        <p style="cursor:pointer" @click="openAddQuestionBox(0)"><a-icon type="check-circle"/> 单选题</p>
                        <p style="cursor:pointer" @click="openAddQuestionBox(1)"><a-icon type="check-square" /> 多选题</p>
                        <p style="cursor:pointer" @click="openAddQuestionBox(2)"><a-icon type="check" /> 判断题</p>
                        <!-- <p style="cursor:pointer;margin-bottom:0" @click="addActionQuestion()"><a-icon type="tool" /> 实操题</p> -->
                    </template>
                    <a-button type="primary">添加题目</a-button>
                </a-popover>
                <a-button type="primary" style="margin:0 10px" @click="uploadBank()"><a-icon type="download"/>导入题目</a-button>
                <download 
                    v-if="questionList.length>0"
                    :name="'导出题目'"
                    :api="'manage/question/export'"
                    :fileName="questionItemTitle+'.xls'"
                    :formData="{'questionLibId':questionItemId}"
                ></download>
                <a-button type="primary" style="margin-left:10px" @click="returnBack()">返回</a-button>
            </div>
            <div slot="table" class="tableWrap">
                <div class="questionBox" v-if="questionList.length>0">
                    <question
                        :subjectList="questionList"
                        :pagination="pagination"
                        @showAnswer="showAnswer"
                        @deleteItem="deleteItem"
                        @editItem="editItem"
                        @selectItem="selectItem"
                    ></question>
                </div>
                <a-empty v-else :description="'暂无数据'"/>
            </div>
        </innerCommon>
        <!-- 弹框--添加/修改题目 -->
        <questionTypeModal
            :question="questionInfo"
            :answer="answer"
            :type="type"
            @cancel="detailBox=false"
            :detailBox="detailBox"
            @selectAnswer="selectAnswer"
            @submitQuestion="submitQuestion"
        ></questionTypeModal>
        <!-- 导入题库 -->
        <a-modal
            style="text-align:center"
            :destroyOnClose='true'
            :confirmLoading="confirmLoading"
            :footer="null"
            :visible="openAddItemBox"
            title="导入题目"
            @cancel="openAddItemBox=false"
            >
                <div class="upload">
                    <p><a-icon type="exclamation-circle" />上传前请先下载模板，按照模板要求将内容录入到模板中</p>
                    <img src="../assets/load_exer.png" alt="">
                    <p>支持格式：xls、xlsx</p>
                    <download 
                        :name="'下载模板'"
                        :api="'manage/question/downloadTemplate'"
                        :fileName="'题库模板.xls'"
                        :isPrimary="false"
                    ></download>
                    <br>
                    <a-upload
                        :fileList="fileList"
                        :remove="handleRemove"
                        :beforeUpload="beforeUpload"
                        accept='.xls,.xlsx'
                        >
                        <a-button style='margin-top:20px;'>
                            <a-icon type="upload" /> 选择文件
                        </a-button>
                        </a-upload>
                        <a-button
                        type="primary"
                        @click="handleUpload"
                        :disabled="fileList.length === 0"
                        :loading="uploading"
                        style="margin-top: 16px"
                        >
                        {{uploading ? '上传中' : '开始上传' }}
                        </a-button>
                </div>
        </a-modal>
    </div>
</template>
<script>
import innerCommon from "@/components/common/innerCommon"
import questionTypeModal from "@/components/common/questionTypeModal"
import question from "@/components/common/question"
import download from "@/components/common/download"
import axios from "axios"
import {
    getQuestionListApi,
    submitQuestionApi,
    deleteQuestionApi,
    updateQuestionApi
    } from "@/request/api"
export default {
    name:"questionAdd",
    components:{innerCommon,questionTypeModal,question,download},
    created(){
        this.questionItemId=this.$route.query.id
        this.questionItemTitle=JSON.parse(this.$route.query.title)
        this.location=[{
            name:"教学课堂管理",
            path:''
        },{
            name:"题库列表",
            path:'/questionBank'
        },{
            name:this.questionItemTitle,
            path:'/questionAdd?id='+this.questionItemId+'&title='+JSON.stringify(this.questionItemTitle)
        }]
        this.init()
    },
    data(){
        return{
            questionItemId:null,
            questionItemTitle:'',
            location:[],
            searchInfo:{
                type:null
            },
            questionList:[],
            isAdd:0,//0是新增 1是修改
            confirmLoading:false,
            questionInfo:{},
            answer:[],
            type:'单选题',
            correct:'',//单多选的答案
            pagination:{pageSize:10,total:10,current:1,onChange: page => {
                this.changePage(page)
            }},
            optionList:['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'],
            questionId:null,
            questionTypeList:[{value:'单选题',types:0},{value:'多选题',types:1},{value:'判断题',types:2}],
            allChecked:false,
            showBtnText:'展开',
            openAddItemBox:false,
            fileList:[],
            uploading:false,
            detailBox:false
        }
    },
    methods:{
        init(){
            this.getToken(getQuestionListApi,{...this.searchInfo,'questionLibId':this.questionItemId},res=>{
                this.pagination.current=1
                this.questionList=res.data.rows.map(item=>({...item,'isShowAnswer':false,'isSelect':false}))
                this.pagination.total=res.data.count
                this.allChecked=false
            })
        },
        openAddQuestionBox(type){
            switch (type) {
                case 0 :this.type="单选题"
                break;
                case 1 :this.type="多选题"
                break;
                case 2 :this.type="判断题"
                break;
                case 3 :this.type="实操题"
                break;
            }
            this.isAdd=0
            this.detailBox=true
            this.questionInfo={'stem':'','analyse':''}
            if(this.type==' 判断题'){
                this.answer=''
            }else{
                this.answer=[{'itemDetails':'','isSelect':false},{'itemDetails':'','isSelect':false},{'itemDetails':'','isSelect':false},{'itemDetails':'','isSelect':false}]
            }   
        },
        // 勾选题目
        selectItem(index,id){
            let target = this.questionList.filter(item=>item.id==id)[0]
            if(target.isSelect){
                target.isSelect=false
            }else{
                target.isSelect=true
            }
        },
        selectKind(data){
            this.searchInfo.type=data
            this.pagination.current=1
            this.init()
        },
        selectAnswer(data){
            if(this.type=='判断题'){
                this.answer=data
            }else{
                this.correct=data
            }
        },
        addActionQuestion(){
            this.$router.push({path:'/questionAction',query:{'id':this.questionItemId,'title':JSON.stringify(this.questionItemTitle)}})
        },
        changePage(data){
            this.pagination.current=data
        },
        // 展示答案
        showAnswer(index){
            let target = this.questionList.filter(item=>item.id == index)[0]
            if(target.isShowAnswer){
                target.isShowAnswer=false
            }else{
                target.isShowAnswer=true
            }
        },
        // 批量删除
        deleteLot(){
            if(this.questionList.filter(item=>item.isSelect==true).length==0){
                this.$message.error('请先勾选需要删除的题目')
                return
            }
            let arr=[]
            this.questionList.filter(item=>item.isSelect==true).forEach(item=>{
                arr.push(item.id)
            })
            this.$confirm({
                title:'确认删除该题目吗?',
                okText:'确认',
                cancelText:'取消',
                onOk:()=>{
                    this.getToken(deleteQuestionApi,{'questionId':arr,'questionLibId':this.questionItemId},()=>{
                        this.$message.success('删除成功')
                        this.init()
                    })
                },
                onCancel() {},
            })
        },
        showAllAnswer(){
            if(this.questionList.filter(item=>item.isShowAnswer==false).length!=0){
                this.questionList.map(item=>item.isShowAnswer=true)
                this.showBtnText='收起'
            }else{
                this.questionList.map(item=>item.isShowAnswer=false)
                this.showBtnText='展开'
            }
        },
        allSelect(){
            if(this.questionList.filter(item=>item.isSelect==false).length!=0){
                this.questionList.map(item=>item.isSelect=true)
                this.allChecked=true
            }else{
                this.questionList.map(item=>item.isSelect=false)
                this.allChecked=false
            }
        },
        deleteItem(data){
            this.$confirm({
                title:'确认删除该题目吗?',
                okText:'确认',
                cancelText:'取消',
                onOk:()=>{
                    this.getToken(deleteQuestionApi,{'questionId':data,'questionLibId':this.questionItemId},()=>{
                        this.$message.success('删除成功')
                        this.init()
                    })
                },
                onCancel() {},
            })
        },
        editItem(item){
            if(item.type==3){
                this.$router.push({path:'/questionAction',query:{'id':this.questionItemId,'item':JSON.stringify(item),'title':JSON.stringify(this.questionItemTitle)}})
                return
            }
            this.questionId=item.id
            this.isAdd=1;
            switch(item.type){
                case 0:this.type='单选题'
                break;
                case 1:this.type='多选题'
                break;
                case 2:this.type='判断题'
                break;
            }
            this.questionInfo={'stem':item.title,'analyse':item.analyse}
            let arr=[]
            if(item.type==0){
                item.option.split('&&').forEach((element,index)=>{
                    arr.push({'itemDetails':element,'isSelect':this.optionList[index]==item.answer})
                })
                this.correct=item.answer
                this.answer=arr
            }else if(item.type==1){
                item.option.split('&&').forEach((element,index)=>{
                    arr.push({'itemDetails':element,'isSelect':item.answer.split('').indexOf(this.optionList[index])==-1?false:true})
                })
                this.correct=item.answer
                this.answer=arr
            }else{
                this.answer=item.answer
            }
            this.detailBox=true;
        },
        // 确认添加题目
        submitQuestion(questionInfo,data,type){
            let formData={
                'libId':this.questionItemId,
                'title':questionInfo.stem,
                'analyse':questionInfo.analyse,
                'answer':type==2?this.answer:this.correct,
                'option':data,
                type
            }
            let api
            if(this.isAdd==0){
                api=submitQuestionApi
            }else{
                api=updateQuestionApi
                formData={...formData,'questionId':this.questionId}
            }
            this.getToken(api,formData,res=>{
                this.$message.success(res.message)
                this.detailBox=false
                this.init()
            })
        },
        uploadBank(){
            this.openAddItemBox=true
        },
        handleRemove(file) {
            const index = this.fileList.indexOf(file);
            const newFileList = this.fileList.slice();
            newFileList.splice(index, 1);
            this.fileList = newFileList
        },
        beforeUpload(file) {
            this.fileList = [file]
            return false;
        },
        handleUpload() {
            const { fileList } = this;
            const formData = new FormData();
            formData.append('questionLibId', this.questionItemId);
            fileList.forEach((file) => {
                formData.append('file', file);
            });
            this.uploading = true
            // You can use any AJAX library you like
            axios.post(window.g.apiUrl+'manage/question/import',formData).then(res=>{
                this.fileList = []
                this.uploading = false
                if(res.data.code==200){
                    this.$message.success(res.data.message);
                }else{
                    this.$message.error(res.data.message);
                }
                this.init()
                this.openAddItemBox=false
            }).catch(()=>{
                this.uploading = false
                this.$message.error('upload failed.');
            });
        },
        returnBack(){
            this.$router.go(-1)
        }
    }
}
</script>
<style lang="stylus" scoped>
    img
        max-width:90%
</style>